const fs = require('fs');
const os = require('os');
const path = require('path')
const util = require('./util')

const CompName = 'index';
const BR = os.EOL;

const FileOption = {
	encoding: 'utf8'
}

const getFiles = (path) => {
	return fs.readdirSync(path);
}

const getText = (uri) => {
	return fs.readFileSync(uri, FileOption).trim();
}

// deal for baidu `fis3` tools
const deleteTemplateOption = (script) => {
	let reg = /\s*template\s*:\s*__inline\(\s*[\'"][^\'"]*[\'"]\s*\)\s*,/;
	return script.replace(reg, '');
}

const wrap = (text, tmpl) => {
	if (text) {
		return tmpl(text);
	} else {
		return '';
	}
}

const JsParser = (path) => {
	let text = getText(path);
	text = deleteTemplateOption(text);
	return wrap(text, text => `<script>${BR}${text}${BR}</script>`);
}

const styleExpendExts = ['.less', '.sass']

const CssParser = (path, ext) => {
	let text = getText(path);
	let lang = '';
	if( styleExpendExts.indexOf( ext ) > -1 ){
		lang = util.trimExt( ext )
	}
	return wrap(text, text => `<style ${lang !=='' ? `lang="${lang}"` : ''}>${BR}${text}${BR}</style>`);
}

const HtmlParser = (path) => {
	let text = getText(path);
	return wrap(text, text => `<template>${BR}${text}${BR}</template>`);
}

const Parser = {
	tmpl: HtmlParser,
	script: JsParser,
	style: CssParser,
};

const getDirName = (dir)=>{
	let dirs = path.normalize( dir ).split( path.sep );
	if( dirs.length > 0){
		return dirs[dirs.length - 1 ];
	}
	return CompName;
};

exports.run = (baseDir, order, supportedExts) => {
	console.log('combinding start')

	let filePaths = getFiles(baseDir || '.');
	// 合并文本内容
	const combind = function (baseDir, content) {
		let compName = getDirName( baseDir );
		console.log(compName)
		fs.writeFileSync(path.join(baseDir, compName + '.vue'), content, FileOption);
	};

	const getFileByExt = ( ext )=>{
		let ret;
		filePaths.some( filePath =>{
			if( ext === path.extname(filePath) ){
				ret = filePath;
				return true;
			}
		});
		return ret;
	};

	const getContent = (exts, parser) => {
		let content = '';
		exts.some(ext => {
			const filePath = getFileByExt(ext);
			if (filePath) {
				content = parser(path.join(baseDir, filePath), ext)
				return true;
			}
		});
		return content;
	};

	var content = order.map( type =>{
		const exts = supportedExts[type]
		const parser = Parser[type];
		return getContent(exts, parser).trim();
	}).filter(text => ([text] + '') !== '').join(BR + BR);

	combind(baseDir, content);

	console.log('combinding end')
}